//! CREATE TABLE功能测试
//!
//! 测试SQL解析器和查询引擎对CREATE TABLE语句的支持

use cdb::{Result, config::DatabaseConfig, sql::QueryEngine, storage::StorageEngine};
use std::sync::Arc;
use parking_lot::RwLock;
use tempfile::TempDir;

#[test]
fn test_create_table_basic() -> Result<()> {
    // 创建临时目录
    let temp_dir = TempDir::new().unwrap();
    let data_dir = temp_dir.path().to_path_buf();

    // 创建数据库配置
    let mut config = DatabaseConfig::default();
    config.data_directory = Some(data_dir);

    // 创建存储引擎和查询引擎
    let storage_engine = Arc::new(RwLock::new(StorageEngine::new(&config)?));
    let mut query_engine = QueryEngine::new(storage_engine);

    // 测试基础CREATE TABLE语句
    let sql = r#"
        CREATE TABLE users (
            id INTEGER PRIMARY KEY,
            name VARCHAR(100) NOT NULL,
            email VARCHAR(255) UNIQUE,
            age INTEGER
        )
    "#;

    let result = query_engine.execute(sql)?;
    
    // 验证结果
    assert_eq!(result.affected_rows, 1);
    assert_eq!(result.rows.len(), 0);
    
    println!("✅ 基础CREATE TABLE测试通过");
    Ok(())
}

#[test]
fn test_create_table_with_constraints() -> Result<()> {
    // 创建临时目录
    let temp_dir = TempDir::new().unwrap();
    let data_dir = temp_dir.path().to_path_buf();

    // 创建数据库配置
    let mut config = DatabaseConfig::default();
    config.data_directory = Some(data_dir);

    // 创建存储引擎和查询引擎
    let storage_engine = Arc::new(RwLock::new(StorageEngine::new(&config)?));
    let mut query_engine = QueryEngine::new(storage_engine);

    // 测试带约束的CREATE TABLE语句
    let sql = r#"
        CREATE TABLE products (
            id SERIAL PRIMARY KEY,
            name VARCHAR(200) NOT NULL,
            price REAL CHECK (price > 0),
            category_id INTEGER,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            CONSTRAINT unique_name UNIQUE (name)
        )
    "#;

    let result = query_engine.execute(sql)?;
    
    // 验证结果
    assert_eq!(result.affected_rows, 1);
    
    println!("✅ 带约束的CREATE TABLE测试通过");
    Ok(())
}

#[test]
fn test_create_table_different_data_types() -> Result<()> {
    // 创建临时目录
    let temp_dir = TempDir::new().unwrap();
    let data_dir = temp_dir.path().to_path_buf();

    // 创建数据库配置
    let mut config = DatabaseConfig::default();
    config.data_directory = Some(data_dir);

    // 创建存储引擎和查询引擎
    let storage_engine = Arc::new(RwLock::new(StorageEngine::new(&config)?));
    let mut query_engine = QueryEngine::new(storage_engine);

    // 测试不同数据类型的CREATE TABLE语句
    let sql = r#"
        CREATE TABLE test_types (
            id INTEGER PRIMARY KEY,
            name TEXT,
            score REAL,
            is_active BOOLEAN,
            birth_date DATE,
            created_at TIMESTAMP,
            description VARCHAR(500)
        )
    "#;

    let result = query_engine.execute(sql)?;
    
    // 验证结果
    assert_eq!(result.affected_rows, 1);
    
    println!("✅ 不同数据类型的CREATE TABLE测试通过");
    Ok(())
}

#[test]
fn test_create_table_duplicate_name() -> Result<()> {
    // 创建临时目录
    let temp_dir = TempDir::new().unwrap();
    let data_dir = temp_dir.path().to_path_buf();

    // 创建数据库配置
    let mut config = DatabaseConfig::default();
    config.data_directory = Some(data_dir);

    // 创建存储引擎和查询引擎
    let storage_engine = Arc::new(RwLock::new(StorageEngine::new(&config)?));
    let mut query_engine = QueryEngine::new(storage_engine);

    // 第一次创建表
    let sql = r#"
        CREATE TABLE duplicate_test (
            id INTEGER PRIMARY KEY,
            name VARCHAR(100)
        )
    "#;

    let result1 = query_engine.execute(sql)?;
    assert_eq!(result1.affected_rows, 1);

    // 第二次创建同名表，应该失败
    let result2 = query_engine.execute(sql);
    assert!(result2.is_err());
    
    println!("✅ 重复表名检测测试通过");
    Ok(())
}

#[test]
fn test_create_table_sql_parsing() -> Result<()> {
    // 创建临时目录
    let temp_dir = TempDir::new().unwrap();
    let data_dir = temp_dir.path().to_path_buf();

    // 创建数据库配置
    let mut config = DatabaseConfig::default();
    config.data_directory = Some(data_dir);

    // 创建存储引擎和查询引擎
    let storage_engine = Arc::new(RwLock::new(StorageEngine::new(&config)?));
    let mut query_engine = QueryEngine::new(storage_engine);

    // 测试复杂的CREATE TABLE语句解析
    let sql = r#"
        CREATE TABLE complex_table (
            id SERIAL PRIMARY KEY,
            user_name VARCHAR(50) NOT NULL UNIQUE,
            email VARCHAR(100) NOT NULL,
            password_hash VARCHAR(255) NOT NULL,
            age INTEGER CHECK (age >= 0 AND age <= 150),
            balance REAL DEFAULT 0.0,
            is_verified BOOLEAN DEFAULT FALSE,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP,
            CONSTRAINT unique_email UNIQUE (email),
            CONSTRAINT positive_balance CHECK (balance >= 0)
        )
    "#;

    let result = query_engine.execute(sql)?;
    
    // 验证结果
    assert_eq!(result.affected_rows, 1);
    
    println!("✅ 复杂CREATE TABLE解析测试通过");
    Ok(())
}

#[test]
fn test_create_table_explain() -> Result<()> {
    // 创建临时目录
    let temp_dir = TempDir::new().unwrap();
    let data_dir = temp_dir.path().to_path_buf();

    // 创建数据库配置
    let mut config = DatabaseConfig::default();
    config.data_directory = Some(data_dir);

    // 创建存储引擎和查询引擎
    let storage_engine = Arc::new(RwLock::new(StorageEngine::new(&config)?));
    let mut query_engine = QueryEngine::new(storage_engine);

    // 测试EXPLAIN CREATE TABLE
    let sql = r#"
        CREATE TABLE explain_test (
            id INTEGER PRIMARY KEY,
            name VARCHAR(100)
        )
    "#;

    let explain_result = query_engine.explain(sql)?;
    
    // 验证解释结果包含CreateTable
    assert!(explain_result.contains("CreateTable"));
    
    println!("✅ CREATE TABLE EXPLAIN测试通过");
    println!("执行计划:\n{}", explain_result);
    Ok(())
}

#[test]
fn test_create_table_performance() -> Result<()> {
    // 创建临时目录
    let temp_dir = TempDir::new().unwrap();
    let data_dir = temp_dir.path().to_path_buf();

    // 创建数据库配置
    let mut config = DatabaseConfig::default();
    config.data_directory = Some(data_dir);

    // 创建存储引擎和查询引擎
    let storage_engine = Arc::new(RwLock::new(StorageEngine::new(&config)?));
    let mut query_engine = QueryEngine::new(storage_engine);

    let start_time = std::time::Instant::now();

    // 创建多个表测试性能
    for i in 0..10 {
        let sql = format!(r#"
            CREATE TABLE perf_test_{} (
                id INTEGER PRIMARY KEY,
                name VARCHAR(100),
                value REAL
            )
        "#, i);

        let result = query_engine.execute(&sql)?;
        assert_eq!(result.affected_rows, 1);
    }

    let elapsed = start_time.elapsed();
    println!("✅ CREATE TABLE性能测试通过");
    println!("创建10个表耗时: {:?}", elapsed);
    println!("平均每个表: {:?}", elapsed / 10);

    // 验证性能要求（每个表创建应该在100ms以内）
    assert!(elapsed.as_millis() < 1000, "CREATE TABLE性能不达标");

    Ok(())
}
